{% extends "base.html" %}

{% block css %}
    <style>
        .table-color {
            border: #1a1e21 solid 1px;
            padding: 5px;
            height: 1.5em;
        }

    </style>
{% endblock %}

{% block main %}
    <div class="container mt-4">
        <form id="form-add" class="form-inline" action="{{ url_full_tag }}" method="post">
            {% csrf_token %}
            <fieldset>
                <div class="row">
                    <div class="col-sm-3 p-2">
                        <label for="obj-sel">{{ tag_cn }}名称</label>
                        <select class="form-control" id="obj-sel" name="obj-sel">
                            {% if obj_spec_dict %}
                                {% for x,y in obj_spec_dict.items %}
                                    {#                                    {% for r in obj %}#}
                                    <option> {{ x }} </option>
                                    {#                                    {% endfor %}#}
                                {% endfor %}
                            {% endif %}
                        </select>
                    </div>
                    <div class="col-sm-3 p-2">
                        <label for="spec-sel">规格</label>
                        <select class="form-control" id="spec-sel" name="spec-sel">
                            <option></option>
                        </select>
                    </div>
                    <div class="col-sm-3 p-2">
                        <label for="num-sel">数量</label>
                        <input name="num-sel" type="number" class="form-control" id="num-sel"
                               placeholder="0" min="0" required>
                    </div>
                    <div class="col-sm-3 p-2">
                        <label>颜色</label>
                        <input type="hidden" name="color-sel" id="color-sel">
                        <div class="dropdown form-control">
                            <button class="btn w-100 h-100" style="padding: 0.6em" type="button"
                                    id="colorDropdownMenuButton"
                                    data-bs-toggle="dropdown" aria-expanded="false">
                            </button>
                            <ul class="dropdown-menu p-1" id="color-dropdown" aria-labelledby="dropdownMenuButton1">

                            </ul>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="offset-sm-9 col-sm-3">
                        <button type="button" id="button-form-add-submit" class="w-100 btn btn-primary">提交</button>
                        <input type="hidden" name="user-in" id="user-in">
                    </div>
                </div>
            </fieldset>
        </form>
    </div>
    <div class="container mt-4">
        <hr/>
        <div class="row justify-content-between align-items-center">
            <div class="col-auto">
                <div class="row">
                    <div class="col-auto pe-1">
                        <div class="btn-group" role="group" aria-label="Basic example">
                            <input id="multiChk" type="checkbox" class="btn-check">
                            <label class="btn btn-outline-primary" for="multiChk">多选</label>

                            <button id="multiDel" type="button" class="cur-hand btn btn-outline-danger disabled">删除
                            </button>
                        </div>
                    </div>
                    <div class="col-auto d-none d-md-block ps-1">
                        <form id="form-search" action="{{ url_full_tag }}" method="get">
                            {% csrf_token %}
                            <div class="input-group">
                                <input name="search" type="text" class="form-control w-auto" placeholder="名称、规格"
                                       aria-label="Search">
                                <button class="btn btn-outline-secondary" type="submit">搜索</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <div class="col-auto ms-0 ps-0">
                <button type="button" class="text-nowrap cur-hand btn btn-outline-success" data-bs-toggle="modal"
                        data-bs-target="#newObjMaterialModal">
                    <span data-feather="plus-square"></span>
                    新增
                </button>
            </div>
        </div>
        <form id="tbl-form" action="{{ url_full_tag }}" method="post">
            {% csrf_token %}

            <table class="table table-striped align-middle">
                <thead>
                <tr>
                    <th class="multiChk d-none">
                        <input id="chkAll" class="form-check-input need-check-delete" type="checkbox">
                    </th>
                    <th>#</th>
                    <th nowrap="nowrap">名称</th>
                    <th nowrap="nowrap">规格</th>
                    <th nowrap="nowrap">颜色</th>
                    <th nowrap="nowrap">库存</th>
                    <th class="text-end">
                    </th>
                </tr>
                </thead>
                <tbody>
                {% if obj_list %}
                    {% for obj in obj_list %}
                        <tr>
                            <td class="multiChk d-none">
                                <input data-name="{{ obj.id }}" class="form-check-input inputChk need-check-delete"
                                       type="checkbox">
                            </td>
                            <td>{{ forloop.counter }}</td>
                            <td>
                                <button onclick="createRemarkModifyModal({{ obj.id }}, '{{ obj.name }}', '{{ obj.spec }}', '{{ obj.color }}', '{{ obj.remarks }}')" type="button"
                                        class="btn btn-sm btn-link text-nowrap text-start">
                                    {{ obj.name }}
                                </button>
                            </td>
                            <td>{{ obj.spec }}</td>
                            <td>
                                <div class="row justify-content-start ms-1">
                                    <div class="table-color"
                                         style="background-color: {{ obj.color }}; border-radius: 0.2em; width: 2em">
                                    </div>
                                </div>
                            </td>
                            <td>{{ obj.stock }}</td>
                            <td>
                                <div id="oper" class="row justify-content-end">
                                    <div id="oper_out" class="col-auto nowrap p-1 me-1">
                                        <button onclick="createOutModal({{ obj.id }})" type="button"
                                                class="w-100 btn btn-sm btn-outline-success text-nowrap"
                                                data-bs-toggle="tooltip"
                                                data-bs-placement="bottom" title="出库">
                                            出库
                                            <span data-feather="chevrons-right"></span>
                                        </button>
                                    </div>
                                    <div id="oper_delete" class="col-auto nowrap p-1 me-1">
                                        <button onclick="deleteGood({{ obj.id }})" type="button"
                                                class="w-100 btn btn-sm btn-outline-danger text-nowrap"
                                                data-bs-toggle="tooltip"
                                                data-bs-placement="bottom" title="删除">
                                            删除
                                            <span data-feather="x-square"></span>
                                        </button>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    {% endfor %}
                {% endif %}
                </tbody>
            </table>

        </form>
        <nav class="row justify-content-center">
            <nav aria-label="Page navigation" class="col-auto">
                <ul class="pagination">

                    {% if obj_list.paginator.num_pages > 3 %}

                        {% if obj_list.has_previous %}
                            <li class="page-item">
                                <a class="page-link" href="?page={{ obj_list.previous_page_number }}"
                                   aria-label="Previous">
                                    <span aria-hidden="true">&laquo;</span>
                                </a>
                            </li>
                        {% else %}
                            <li class="page-item disabled">
                                <a class="page-link" href="?page=#" aria-label="Previous">
                                    <span aria-hidden="true">&laquo;</span>
                                </a>
                            </li>
                        {% endif %}
                    {% endif %}

                    {% autoescape off %}

                        {% if pprev_page_html and not next_page_html %}
                            {{ pprev_page_html }}
                        {% endif %}

                        {% if prev_page_html %}
                            {{ prev_page_html }}
                        {% endif %}

                        {{ current_page_html }}

                        {% if next_page_html %}
                            {{ next_page_html }}
                        {% endif %}

                        {% if nnext_page_html and not prev_page_html %}
                            {{ nnext_page_html }}
                        {% endif %}

                    {% endautoescape %}

                    {% if obj_list.paginator.num_pages > 3 %}
                        {% if obj_list.has_next %}
                            <li class="page-item">
                                <a class="page-link" href="?page={{ obj_list.next_page_number }}" aria-label="Next">
                                    <span aria-hidden="true">&raquo;</span>
                                </a>
                            </li>
                        {% elif obj_list.has_previous %}
                            <li class="page-item disabled">
                                <a class="page-link" href="?page=#" aria-label="Next">
                                    <span aria-hidden="true">&raquo;</span>
                                </a>
                            </li>
                        {% endif %}

                    {% endif %}
                </ul>
            </nav>
        </nav>
    </div>

    <!-- Modal : modify remark -->
    <div class="modal fade" id="remarkModifyModal" tabindex="-1" aria-labelledby="remarkModifyModalLabel"
         aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form id="form-remark-modify" class="form-inline" action="{{ url_full_tag }}" method="post">
                    <div class="modal-header">
                        <h5 class="modal-title" id="remarkModifyModalLabel">备注</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="container-fluid">
                            {% csrf_token %}
                            <fieldset>
                                <div class="row">
                                    <div class="col p-2">
                                        <label for="remark-modify"></label>
                                        <textarea id="remark-modify" name="remark-modify" class="form-control"></textarea>
                                        <input type="hidden" name="id-remark" id="id-remark">
                                    </div>
                                </div>
                            </fieldset>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                        <button type="button" id="button-form-remark-modify-submit" class="btn btn-primary">保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal -->
    <div class="modal fade" id="newObjMaterialModal" tabindex="-1" aria-labelledby="newObjMaterialModalLabel"
         aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form id="form-new" class="form-inline" action="{{ url_full_tag }}" method="post">
                    <div class="modal-header">
                        <h5 class="modal-title" id="newObjMaterialModalLabel">新增{{ tag_cn }}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="container-fluid">
                            {% csrf_token %}
                            <fieldset>
                                <div class="row">
                                    <div class="col-sm-3 p-2">
                                        <label for="obj-new">{{ tag_cn }}</label>
                                        <input class="form-control" id="obj-new" name="obj-new">
                                    </div>
                                    <div class="col-sm-3 p-2">
                                        <label for="spec-new">规格</label>
                                        <input class="form-control" id="spec-new" name="spec-new">
                                    </div>
                                    <div class="col-sm-3 p-2">
                                        <label for="num-new">数量</label>
                                        <input name="num-new" type="number" class="form-control" id="num-new"
                                               placeholder="0" min="0" required>
                                    </div>
                                    <div class="col-sm-3 p-2">
                                        <label for="color-new">颜色</label>
                                        <input name="color-new" type="color" class="form-control" id="color-new"
                                               placeholder="0">
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col p-2">
                                        <label for="remark-new">备注</label>
                                        <textarea id="remark-new" name="remark-new" class="form-control"></textarea>
                                    </div>
                                </div>
                            </fieldset>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                        <button type="button" id="button-form-new-submit" class="btn btn-primary">保存</button>
                        <input type="hidden" name="user-new" id="user-new">
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal : out of stock -->
    <div class="modal fade" id="outOfStockModal" tabindex="-1" aria-labelledby="outOfStockModalLabel"
         aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form id="form-out" class="form-inline" action="{{ url_full_tag }}" method="post">
                    <div class="modal-header">
                        <h5 class="modal-title" id="outOfStockModalLabel">出库</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="container-fluid">
                            {% csrf_token %}
                            <fieldset>
                                <div class="row">
                                    <div class="col-sm-3 p-2">
                                        <label>数量</label>
                                        <input name="num-out" type="number" class="form-control" id="num-out"
                                               placeholder="0" min="0" required>
                                        <input type="hidden" name="id-out" id="id-out">
                                        <input type="hidden" name="user-out" id="user-out">
                                    </div>
                                </div>
                            </fieldset>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                        <button type="button" id="button-form-out-submit" class="btn btn-primary">保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>


    <!-- Modal : delete -->
    <div class="modal fade" id="deleteAllModal" tabindex="-1" aria-labelledby="deleteAllModalLabel"
         aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <form id="form-delete-all" class="form-inline" action="{{ url_full_tag }}" method="post">
                    <div class="modal-header">
                        <h5 class="modal-title" id="deleteAllModalLabel">删除</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="container-fluid">
                            {% csrf_token %}
                            <fieldset>
                                <div class="row">
                                    <div class="col-sm-9 p-2">
                                        <label for="password" class="p-2">请输入密码确认操作</label>
                                        <input name="password" type="password" class="form-control" id="password"
                                               required>
                                        <input type="hidden" name="user" id="user">
                                    </div>
                                </div>
                            </fieldset>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                        <button type="button" id="button-form-delete-all-submit" class="btn btn-warning">删除</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal : delete -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel"
         aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <form id="form-delete" class="form-inline" action="{{ url_full_tag }}" method="post">
                    <div class="modal-header">
                        <h5 class="modal-title" id="deleteModalLabel">删除</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="container-fluid">
                            {% csrf_token %}
                            <fieldset>
                                <div class="row">
                                    <div class="col-sm-9 p-2">
                                        <label for="password" class="p-2">请输入密码确认操作</label>
                                        <input name="password" type="password" class="form-control" id="password1"
                                               required>
                                        <input type="hidden" name="user" id="user1">
                                        <input type="hidden" name="id-delete" id="id-delete">
                                    </div>
                                </div>
                            </fieldset>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                        <button type="button" id="button-form-delete-submit" class="btn btn-warning">删除</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

{% endblock %}

{% block set_curPage %}
    curPage = document.getElementById("{{ url_name }}")
{% endblock %}

{% block javascript %}
    <script>
        function removeOptions(selectElement) {
            var i, L = selectElement.options.length - 1;
            for (i = L; i >= 0; i--) {
                selectElement.remove(i);
            }
        }

        let obj_spec = {
            {% if obj_spec_dict %}
                {% for k,v in obj_spec_dict.items %}
                    "{{ k }}": [
                        {% for i in v %}
                            '{{ i }}',
                        {% endfor %}
                    ],
                {% endfor %}
            {% endif %}
        }


        let obj_color = {
            {% if obj_spec_dict %}
                {% for k,v in obj_color_dict.items %}
                    "{{ k }}": [
                        {% for i in v %}
                            '{{ i }}',
                        {% endfor %}
                    ],
                {% endfor %}
            {% endif %}
        }

        let sel = document.querySelector('#obj-sel')
        let spec_sel = document.querySelector('#spec-sel')
        let color_dropdown = $('#color-dropdown')


        function color_need_change(event) {
            if (sel.selectedOptions.length >= 1) {
                const spec_sel = document.querySelector('#spec-sel')
                let cur = sel.selectedOptions[0].value

                let cur_spec = spec_sel.selectedOptions[0].value
                let color_key = cur + cur_spec
                let color_opt_arr = obj_color[color_key]

                color_dropdown.empty()
                for (let i = 0; i < color_opt_arr.length; i++) {
                    color_dropdown.append(' <li> <a class="dropdown-item mb-1" style="background-color: {0}; height: 20px; border: #676462 solid 1px" href="#" onclick="change_col_dropdown_color(\'{0}\')"></a> </li>'.format(color_opt_arr[i]))
                }

                let dropdown = $("#colorDropdownMenuButton")
                let scolor = color_dropdown.children().first().children().first().css('background-color')
                if (scolor) {
                    let rgb = new RGBColor(scolor)
                    change_col_dropdown_color(rgb.toHex())
                }
            }
        }

        function change_evt(event) {
            if (sel.selectedOptions.length >= 1) {
                const spec_sel = document.querySelector('#spec-sel')
                let cur = sel.selectedOptions[0].value
                let opt_arr = obj_spec[cur]
                removeOptions(spec_sel)
                for (let i = 0; i < opt_arr.length; i++) {
                    op = document.createElement("option")
                    op.innerText = opt_arr[i]
                    spec_sel.append(op)
                }


                color_need_change(event)
            }
        }


        sel.addEventListener('change', change_evt)
        spec_sel.addEventListener('change', color_need_change)

        function change_col_dropdown_color(color) {
            let dropdown = $("#colorDropdownMenuButton")
            dropdown.css("background", color)
            dropdown.css("border", "#676462FF solid 1px")
            $("#color-sel").val(color)
        }


        $('#button-form-add-submit').click(function (event) {
            if (isNullOrSpace($('#obj-sel').val())) {
                alert('不合法的名称!')
                return;
            }
            if (isNullOrSpace($('#spec-sel').val())) {
                alert('不合法的规格!')
                return;
            }
            if (isNullOrSpace($('#color-sel').val())) {
                alert('不合法的颜色!')
                return;
            }
            let num = $('#num-sel').val()
            if (num === '' || parseInt(num) <= 0) {
                alert('不合法的数量!')
                return
            }
            $('#user-in').val("{{ user.get_username }}")
            $('#form-add').submit()
        })

        $('#button-form-new-submit').click(function (event) {
            if (isNullOrSpace($('#obj-new').val())) {
                alert('不合法的名称!')
                return;
            }
            if (isNullOrSpace($('#spec-new').val())) {
                alert('不合法的规格!')
                return;
            }
            if (isNullOrSpace($('#color-new').val())) {
                alert('不合法的颜色!')
                return;
            }
            let num = $('#num-new').val()
            if (num === '' || parseInt(num) <= 0) {
                alert('不合法的数量!')
                return
            }
            $('#user-new').val("{{ user.get_username }}")
            $('#form-new').submit()
        })


        let outModal = new bootstrap.Modal(document.getElementById('outOfStockModal'))
        let remarkModifyModal = new bootstrap.Modal(document.getElementById('remarkModifyModal'))
        let deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'))
        let deleteAllModal = new bootstrap.Modal(document.getElementById('deleteAllModal'))

        function createRemarkModifyModal(obj_id, name, spec, color, remarks) {
            function outClickListener() {
                $('#id-remark').val(obj_id)
                $('#form-remark-modify').submit()
            }

            let form_out = $('#button-form-remark-modify-submit')

            form_out.off("click")
            form_out.on("click", outClickListener)

            $('#remarkModifyModalLabel').text('备注（{0}, {1}, {2}）'.format(name, spec, color))
            $('#remark-modify').text(remarks)
            remarkModifyModal.show()
        }


        function createOutModal(obj_id) {
            function outClickListener() {

                let num = $('#num-out').val()
                if (num === '' || parseInt(num) <= 0) {
                    alert('不合法的数量!')
                    return
                }
                $('#id-out').val(obj_id)
                $('#user-out').val("{{ user.get_username }}")
                $('#form-out').submit()
            }

            let form_out = $('#button-form-out-submit')

            form_out.off("click")
            form_out.on("click", outClickListener)

            outModal.show()
        }

        function deleteGood(obj_id) {

            let form_delete = $('#button-form-delete-submit')

            form_delete.off("click")
            form_delete.on("click", function () {
                $('#id-delete').val(obj_id)
                $('#user1').val("{{ user.get_username }}")
                $('#form-delete').submit()
            })

            deleteModal.show()

        }

        let chkAll = $('#chkAll')
        let inputChk = $(".need-check-delete")
        let multiDel = $('#multiDel')

        $('#multiChk').on("click", function (event) {
            let chks = $('.multiChk')
            if (chks.hasClass('d-none')) {
                chks.removeClass('d-none')
            } else {
                chks.addClass('d-none')
                multiDel.addClass('disabled')
                chkAll.prop('checked', false)
                inputChk.prop('checked', false)
            }
        })

        multiDel.on("click", function () {

            let form_delete = $('#button-form-delete-all-submit')
            let form = $('#form-delete-all')

            form_delete.off("click")
            form_delete.on("click", function () {
                let form_delete = $('#tbl-form')
                let chkItems = $('.inputChk:checked')
                console.log(chkItems.length)
                let i, len = chkItems.length
                let all = ''
                for (i = 0; i < len; i++) {
                    all += chkItems[i].getAttribute('data-name') + ','
                }
                let nItm = "<input type='hidden' name='delete-multi' value='{0}'>".format(all)
                form.append(
                    nItm
                )
                $('#user').val("{{ user.get_username }}")
                form.submit()


            })

            deleteAllModal.show()
        })

        chkAll.on("click", function () {
            if (chkAll.prop('checked')) {
                inputChk.prop('checked', true)
            } else {
                inputChk.prop('checked', false)
            }
        })

        inputChk.on("click", function () {
            if ($('.inputChk:checked').length >= 1) {
                $('#multiDel').removeClass('disabled')
            } else {
                $('#multiDel').addClass('disabled')
            }
        })

        $('form input').keydown(function (e) {
            if (e.keyCode === 13) {
                e.preventDefault();
                return false;
            }
        });
        $(document).ready(function () {

            change_evt()
            // prevent re-submit on refreshing
            // Refer to https://stackoverflow.com/questions/6320113/how-to-prevent-form-resubmission-when-page-is-refreshed-f5-ctrlr
            if (window.history.replaceState) {
                window.history.replaceState(null, null, window.location.href);
            }

            let err_msg = "{{ err_msg }}";
            if (err_msg !== "") {
                alert(err_msg)
            }
        })

    </script>
{% endblock %}

